/*
 * @Description: 
 * @Autor: 商晓彬
 * @Date: 2021-07-15 16:00:37
 * @LastEditors: 商晓彬
 * @LastEditTime: 2022-02-21 10:46:03
 */
import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Input, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import { MessageService } from '@abp/message/message.service';
import { finalize } from 'rxjs/operators';
import { Table } from 'primeng/components/table/table';
import { Paginator } from 'primeng/components/paginator/paginator';
import { LazyLoadEvent } from 'primeng/api';
import { BomContentServiceProxy, BomEditChildData, BomDesignDetailDto, MaterialsServiceProxy, MaterialsEditContentDto,BomChangeServiceProxy } from '@shared/service-proxies/service-proxies';

@Component({
    selector: 'materialSon',
    templateUrl: './material-son.component.html',
    styleUrls: ['./material-son.component.less']
})
export class MaterialSonComponent extends AppComponentBase {
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;
    //引入子组件
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Input() editData: any;  //行数据
    @Input() title: string;  //标题
    @Input() flag: boolean;  //新增修改
    @Input() addSecond: any;
    @Input() nodeLevel: any;
    @Input() type: any;
    saving = false;
    active = false;
    addFlag = false;
    form = { materialCode: '', materialname: '', model: '', part: '' };
    addForm = {
        materialCode: '', materialname: '', materialProperties: 0,
        materialModel: '', isUsed: true, remark: ''
    };
    search = {
        materialCode:undefined,materialname:undefined
    };
    materialPropertiesOption = [
        {
            label: '请选择',
            value: ''
        }, {
            label: '整装',
            value: 0
        }, {
            label: '芯级',
            value: 4
        },
        {
            label: '部件',
            value: 1
        }, {
            label: '组件',
            value: 2
        }, {
            label: '零件',
            value: 3
        }
    ];
    selectRow: any = [];
    saveFlag = true;
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _bomContentServiceProxy: BomContentServiceProxy,
        private _materialsServiceProxy: MaterialsServiceProxy,
        private _bomChangeServiceProxy: BomChangeServiceProxy,
    ) {
        super(injector);
    }
    closeParent(event) {
        this.addForm.isUsed = true;
        this.addForm.materialCode = undefined;
        this.addForm.materialModel = undefined;
        if (this.editData[0].id == this.editData[1].id) {
            this.addForm.materialProperties = 4;
        } else {
            this.addForm.materialProperties = 1;
        }
        this.addForm.materialname = undefined;
        this.addForm.remark = undefined;
        this.addFlag = false;
    }
    getAttribute(row) {
        switch (row) {
            case 0:
                return '整装';
            case 4:
                return '芯级';
            case 1:
                return '部件';
            case 2:
                return '组件';
            case 3:
                return '零件';
            default:
                return null
        }
    }
    ngOnInit() {
    }
    //打开弹窗
    onShown(): void {
        if (this.editData[0].id == this.editData[1].id) {
            this.addForm.materialProperties = 4;
        } else {
            this.addForm.materialProperties = 1;
        }
        this.form.materialCode = this.editData[0].materialNo;
        this.form.materialname = this.editData[0].materialName;
        this.form.model = this.editData.model;
        this.form.part = this.editData.isKeyPart == 'False' ? '否' : '是';
    }
    //查看新增任务
    show(): void {
        this.active = true;
        this.modal.show();
    }
    //关闭事件
    close(): void {
        if (this.addFlag) {
            this._messageService.error("新增内容未保存！");
            return;
        }
        this.form.materialCode = undefined;
        this.form.materialname = undefined;
        this.form.model = undefined;
        this.form.part = undefined;
        this.selectRow = [];
        //清空form表单
        this.active = false;
        this.modalSave.emit(this.selectRow);
        this.modal.hide();
    }
    save() {
        for (const item of this.selectRow) {
            if (item.id == this.editData[0].id) {
                this._messageService.warn("添加子级物料结构包含该物料的父级物料，请重新选择！");
                return;
            }
        }
        let child = this.editData[2];
        let data = [];
        if (this.editData[1].sonLevel == 1) {
            for (let i = 0; i < this.selectRow.length; i++) {
                let item = this.selectRow[i];
                let son = new BomEditChildData();
                if (child == undefined) {
                    son.levelRelationship = this.editData[1].levelRelationship + '.' + (i + 1);
                } else {
                    son.levelRelationship = this.editData[1].levelRelationship + '.' + (i + 1 + child.index);
                }
                son.id = "00000000-0000-0000-0000-000000000000";
                son.parentMaterialId = "00000000-0000-0000-0000-000000000000";
                son.parentId = '00000000-0000-0000-0000-000000000000';
                son.materialId = item.id;
                son.unit1BomDosage = 1;// 默认为1
                son.remark = item.remark;
                son.sonLevel = 2;
                let guid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                let guidCode = guid + guid + "-" + guid + "-" + guid + "-" + guid + "-" + guid + guid + guid;
                son.sonId = guidCode;
                //展示数据
                son.materialNo = item.materialNo;
                son.materialName = item.materialName;
                son.model = item.model;
                son.unitName = item.unitName;
                son.versionNo = item.versionNo;
                son.attribute = item.attribute;
                son.materialTypeName = item.materialTypeName;
                son.materialSegmentationName = item.materialSegmentationName;
                son.isKeyPart = item.isKeyPart;
                data.push(son);
            }
        } else if (this.editData[1].sonLevel == 2) {
            for (let i = 0; i < this.selectRow.length; i++) {
                let item = this.selectRow[i];
                let son = new BomEditChildData();
                if (child == undefined) {
                    son.levelRelationship = this.editData[1].levelRelationship + '.' + (i + 1);
                } else {
                    son.levelRelationship = this.editData[1].levelRelationship + '.' + (i + 1 + child.index);
                }
                son.id = "00000000-0000-0000-0000-000000000000";
                son.parentMaterialId = "00000000-0000-0000-0000-000000000000";
                son.parentId = '00000000-0000-0000-0000-000000000000';
                son.materialId = item.id;
                son.unit1BomDosage = 1;// 默认为1
                son.remark = item.remark;
                son.sonLevel = 3;
                let guid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                let guidCode = guid + guid + "-" + guid + "-" + guid + "-" + guid + "-" + guid + guid + guid;
                son.sonId = guidCode;
                //展示数据
                son.materialNo = item.materialNo;
                son.materialName = item.materialName;
                son.model = item.model;
                son.unitName = item.unitName;
                son.versionNo = item.versionNo;
                son.attribute = item.attribute;
                son.materialTypeName = item.materialTypeName;
                son.materialSegmentationName = item.materialSegmentationName;
                son.isKeyPart = item.isKeyPart;
                data.push(son);
            }
        } else if (this.editData[1].sonLevel == 3) {
            for (let i = 0; i < this.selectRow.length; i++) {
                let item = this.selectRow[i];
                let son = new BomEditChildData();
                if (child == undefined) {
                    son.levelRelationship = this.editData[1].levelRelationship + '.' + (i + 1);
                } else {
                    son.levelRelationship = this.editData[1].levelRelationship + '.' + (i + 1 + child.index);
                }
                son.id = "00000000-0000-0000-0000-000000000000";
                son.parentMaterialId = "00000000-0000-0000-0000-000000000000";
                son.parentId = '00000000-0000-0000-0000-000000000000';
                son.materialId = item.id;
                son.unit1BomDosage = 1;// 默认为1
                son.remark = item.remark;
                son.sonLevel = 4;
                let guid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                let guidCode = guid + guid + "-" + guid + "-" + guid + "-" + guid + "-" + guid + guid + guid;
                son.sonId = guidCode;
                //展示数据
                son.materialNo = item.materialNo;
                son.materialName = item.materialName;
                son.model = item.model;
                son.unitName = item.unitName;
                son.versionNo = item.versionNo;
                son.attribute = item.attribute;
                son.materialTypeName = item.materialTypeName;
                son.materialSegmentationName = item.materialSegmentationName;
                son.isKeyPart = item.isKeyPart;
                data.push(son);
            }
        } else if (this.editData[1].sonLevel == 4) {
            for (let i = 0; i < this.selectRow.length; i++) {
                let item = this.selectRow[i];
                let son = new BomEditChildData();
                if (child == undefined) {
                    son.levelRelationship = this.editData[1].levelRelationship + '.' + (i + 1);
                } else {
                    son.levelRelationship = this.editData[1].levelRelationship + '.' + (i + 1 + child.index);
                }
                son.id = "00000000-0000-0000-0000-000000000000";
                son.parentMaterialId = "00000000-0000-0000-0000-000000000000";
                son.parentId = '00000000-0000-0000-0000-000000000000';
                son.materialId = item.id;
                son.unit1BomDosage = 1;// 默认为1
                son.remark = item.remark;
                son.sonLevel = 5;
                let guid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                let guidCode = guid + guid + "-" + guid + "-" + guid + "-" + guid + "-" + guid + guid + guid;
                son.sonId = guidCode;
                //展示数据
                son.materialNo = item.materialNo;
                son.materialName = item.materialName;
                son.model = item.model;
                son.unitName = item.unitName;
                son.versionNo = item.versionNo;
                son.attribute = item.attribute;
                son.materialTypeName = item.materialTypeName;
                son.materialSegmentationName = item.materialSegmentationName;
                son.isKeyPart = item.isKeyPart;
                data.push(son);
            }

        }
        if (this.flag) {
            data = this.selectRow;
            let input = [];
            for (const item of this.selectRow) {
                let inner = new BomDesignDetailDto();
                inner.materialId = item.id;
                //2021-10-06曲冰添加
                inner.materialProperty = item.materialProperty
                input.push(inner);
            };
            if (this.addSecond == undefined) {
                if (this.nodeLevel == '组件' || this.nodeLevel == '部件') {
                    if (this.saveFlag) {
                        this.saveFlag = false;
                        let guid = this.editData[1].id;
                        this._bomContentServiceProxy.createChildrenNode(
                            input,
                            guid
                        ).pipe(finalize(() => { this.saving = false; }))
                            .subscribe((result) => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    this._messageService.success('保存成功');
                                    this.modalSave.emit(result.children);
                                    this.closeSave();
                                } else {
                                    this._messageService.error(result.message)
                                }
                            });
                    }
                } else {
                    if (this.saveFlag) {
                        this.saveFlag = false;
                        let guid = this.editData[1].id;
                        this._bomContentServiceProxy.createChildrenNode(
                            input,
                            guid
                        ).pipe(finalize(() => { this.saving = false; }))
                            .subscribe((result) => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    this._messageService.success('保存成功');
                                    this.modalSave.emit(result.children);
                                    this.closeSave();
                                } else {
                                    this._messageService.error(result.message)
                                }
                            });
                    }
                }
            } else {
                if (this.saveFlag) {
                    this.saveFlag = false;
                    let guid = this.addSecond.id;
                    this._bomContentServiceProxy.createChildrenTopNode(
                        input,
                        guid
                    ).pipe(finalize(() => { this.saving = false; }))
                        .subscribe((result) => {
                            this.saveFlag = true;
                            if (result.code == 0) {
                                this._messageService.success('保存成功');
                                this.modalSave.emit(result.children);
                                this.closeSave();
                            } else {
                                this._messageService.error(result.message)
                            }
                        });
                }
            }
        } else {
            this.modalSave.emit(data);
            this.closeSave();
        }

    }
    closeSave() {
        if (this.addFlag) {
            this._messageService.error("新增内容未保存！");
            return;
        }
        this.form.materialCode = undefined;
        this.form.materialname = undefined;
        this.form.model = undefined;
        this.form.part = undefined;
        this.selectRow = [];
        //清空form表单
        this.active = false;
        this.modal.hide();
    }
    resert() {
        this.search.materialCode = undefined;
        this.search.materialname = undefined;
    }
    getTableList(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        if (this.nodeLevel == '组件' || this.nodeLevel == '部件') {
            this._bomChangeServiceProxy.getSelectChildMaterialsContentChange(
                undefined,
                undefined,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
        } else {
            this._bomContentServiceProxy.getSelectChildMaterials(
                this.type,//右上角子集为1下面添加子集为2
                this.search.materialCode,
                this.search.materialname,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
        }
        
    }
    addSon() {
        //创建新物料
        this.addFlag = true;
    }
    //保存任务
    addSave(): void {
        let input = new MaterialsEditContentDto();
        input.materialNo = this.addForm.materialCode;
        input.materialName = this.addForm.materialname;
        input.materialProperty = this.addForm.materialProperties;
        input.model = this.addForm.materialModel;
        input.remark = this.addForm.remark;
        if (this.addForm.isUsed) {
            input.isUsed = 1;
        } else {
            input.isUsed = 0;
        }
        if (this.saveFlag) {
            this.saveFlag = false;
            this._materialsServiceProxy.createOrUpdateMaterialsContent(input)
                .pipe(finalize(() => { this.saving = false; }))
                .subscribe((result) => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this._messageService.success('保存成功');
                        this.addForm.isUsed = true;
                        this.addForm.materialCode = undefined;
                        this.addForm.materialModel = undefined;
                        if (this.editData[0].id == this.editData[1].id) {
                            this.addForm.materialProperties = 4;
                        } else {
                            this.addForm.materialProperties = 1;
                        }
                        this.addForm.materialname = undefined;
                        this.addForm.remark = undefined;
                        this.addFlag = false;
                        this.getTableList();
                    } else {
                        this._messageService.error(result.message)
                    }

                });
        }

    }
}
